﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace Manox.Libs.Foundation
{
    /// <summary>
    /// Network message translator.
    /// </summary>
    public class TypeTranslator
    {
        /// <summary>Classes.</summary>
        private Dictionary<byte, Delegate> Classes;
        /// <summary>Types.</summary>
        private Dictionary<Type, byte> Types;

        
        /// <summary>
        /// Constructor.
        /// </summary>
        public TypeTranslator()
        {
            this.Classes = new Dictionary<byte, Delegate>();
            this.Types = new Dictionary<Type, byte>();
        }

        /// <summary>
        /// Register type.
        /// </summary>        
        public void RegisterType<T>()
        {
            if (this.Types.ContainsKey(typeof(T)))
                return;

            byte typeId = (byte)(this.Classes.Count + 1);

            this.Classes.Add(typeId, Expression.Lambda(Expression.New(typeof(T))).Compile());

            this.Types.Add(typeof(T), typeId);
        }

        /// <summary>
        /// Get type id.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public byte GetTypeId(Type type)
        {
            if (this.Types.ContainsKey(type))
                return this.Types[type];

            return 0;
        }

        /// <summary>
        /// Get new instance.
        /// </summary>
        /// <param name="messageType"></param>
        /// <returns></returns>
        public object GetInstance(byte typeId)
        {
            if (this.Classes.ContainsKey(typeId))
                return this.Classes[typeId].DynamicInvoke();

            return null;
        }
    }
}
